package com.software.levelupandroid.taskCount.view;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.mikhaellopez.circularprogressbar.CircularProgressBar;
import com.software.levelupandroid.R;
import com.software.levelupandroid.entity.Task;
import com.software.levelupandroid.home.HomeActivity;
import com.software.levelupandroid.taskIssue.view.activity.TaskIssueActivity;
import com.software.levelupandroid.utils.DateUtil;
import com.software.levelupandroid.utils.StringUtil;

import java.io.Serializable;

public class TaskCountActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private TextView tvTaskCountTitle;
    private TextView tvTaskCountContent;
    private TextView tvTaskCountDate;
    private TextView tvTaskCountStart;
    private TextView tvTaskCountEnd;
    private CircularProgressBar taskCountCircularProgressBar;
    private TextView tvTimeDownShow;
    private TextView tvTaskCountTag;
    private TextView tvTaskCountType;
    private TextView tvTaskCountPriority;
    private Button btnTaskCountFinish;
    private Button btnTaskCountDelay;
    private CountDownTimer countDownTimer;
    private Task task;
    private Long longDuration;
    private int progress = 0;
    private boolean isPaused = false;

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_count);

        Intent intent = getIntent();
        task = (Task) intent.getSerializableExtra("task");
        if (task == null){
            task = new Task();
        }

        //控件绑定
        initView();
        //初始化toolbar
        initToolbar();
        //初始化内容
        initContent();

//        longDuration = DateUtil.getLongDuration("2024年05月27日 07:00", "2024年05月27日 07:30");

        //开启倒计时
        counter(longDuration);

        //设置监听器
        setListener();

    }

    /**
     * 设置监听器
     */
    private void setListener() {
        //设置任务的完成监听器
        btnTaskCountFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                AlertDialog alertDialog2 = new AlertDialog.Builder(TaskCountActivity.this)
                        .setTitle("是否确定任务完成")
                        .setMessage("提前" + tvTimeDownShow.getText() + "完成")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                pauseCountDown();
                                btnTaskCountDelay.setText("开始");
                                tvTimeDownShow.setText("任务完成");
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        })
                        .create();
                alertDialog2.show();
            }
        });

        //设置任务延迟的监听器
        btnTaskCountDelay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isPaused){
                    btnTaskCountDelay.setText("暂停");
                    resumeCountDown();
                }else {
                    btnTaskCountDelay.setText("开始");
                    pauseCountDown();
                }
            }
        });
    }

    /**
     * 设置进度条倒计时
     * @param totalDuration
     */
    private void counter(Long totalDuration) {
        taskCountCircularProgressBar.setProgress(progress);

        if (countDownTimer != null){
            countDownTimer.cancel(); // 如果已经有一个正在运行的计时器，先取消它
        }

        long newDuration = totalDuration;
        if (longDuration > 0){
            newDuration = longDuration;
        }

        countDownTimer = new CountDownTimer(newDuration, 1000) {
            @Override
            public void onTick(long l) {
                //计算剩余的小时、分钟、和秒
                int hours = (int) ((l/(1000*60*60))%24);
                int minutes = (int) ((l/(1000*60))%60);
                int seconds = (int) ((l/ 1000) % 60);

                //格式化为HH:mm:ss
                String timeLeftFormatted = String.format("%02d:%02d:%02d", hours, minutes, seconds);

                if (!isPaused){
                    longDuration = l;
                    tvTimeDownShow.setText(timeLeftFormatted);
                }

                progress = (int) ((totalDuration - l)/(float)totalDuration*100);
                taskCountCircularProgressBar.setProgress(progress);
            }

            @Override
            public void onFinish() {
                taskCountCircularProgressBar.setProgress(100);
                tvTimeDownShow.setText("00:00:00");
            }
        };
        countDownTimer.start();
    }

    /**
     * 暂停倒计时
     */
    public void pauseCountDown(){
        isPaused = true;
        countDownTimer.cancel();
    }

    /**
     * 恢复倒计时
     */
    public void resumeCountDown(){
        isPaused = false;
        counter(longDuration);
    }

    /**
     * 初始化内容
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void initContent() {
        tvTaskCountTitle.setText(task.getTaskTitle());
        tvTaskCountContent.setText(task.getContent());
        String[] timeStart = task.getStartTime().split(" ");
        String[] timeEnd = task.getEndTime().split(" ");
        if (StringUtil.isNotEmpty(timeStart[0]) && StringUtil.isNotEmpty(timeEnd[0])){
            if (timeStart[0].equals(timeEnd[0])){
                tvTaskCountDate.setText(timeStart[0]);
                tvTaskCountStart.setText(timeStart[1]);
                tvTaskCountEnd.setText(timeEnd[1]);
            }else {
                tvTaskCountStart.setText(task.getStartTime());
                tvTaskCountEnd.setText(task.getEndTime());
            }
        }
        if (task.getTag() != null){
//            tvTaskCountTag.setText();
        }
//        tvTaskCountType.setText("");
        switch (task.getPriority()){
            case 0:
                tvTaskCountPriority.setText("不重要不紧急");
                break;
            case 1:
                tvTaskCountPriority.setText("重要不紧急");
                break;
            case 2:
                tvTaskCountPriority.setText("不重要紧急");
                break;
            case 3:
                tvTaskCountPriority.setText("重要且紧急");
                break;
            default:
                break;
        }
        longDuration = DateUtil.getLongDuration(task.getStartTime(), task.getEndTime());

    }

    /**
     * 初始化工具栏
     */
    private void initToolbar() {
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null)
            actionBar.setDisplayShowTitleEnabled(false);
    }

    /**
     * 加载toolbar上的菜单资源
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_menu_count_timing_task,menu);
        return true;
    }

    /**
     * 设置菜单项中的点击事件
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.menu_count_edit:
                Intent intent = new Intent(TaskCountActivity.this, TaskIssueActivity.class);
                intent.putExtra("task", task);
                intent.putExtra("flag", 1);
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * 导航到首页
     * @return
     */
    @Override
    public boolean onSupportNavigateUp() {
        Intent intent = new Intent(TaskCountActivity.this, HomeActivity.class);
        startActivity(intent);
        return true;
    }

    /**
     * 控件绑定
     */
    private void initView() {
        toolbar = findViewById(R.id.toolbar_taskCount);
        tvTaskCountTitle = findViewById(R.id.tv_taskCount_title);
        tvTaskCountContent = findViewById(R.id.tv_taskCount_content);
        tvTaskCountDate = findViewById(R.id.tv_taskCount_date);
        tvTaskCountStart = findViewById(R.id.tv_taskCount_start);
        tvTaskCountEnd = findViewById(R.id.tv_taskCount_end);
        taskCountCircularProgressBar = findViewById(R.id.taskCount_circularProgressBar);
        tvTimeDownShow = findViewById(R.id.tv_timeDown_show);
        tvTaskCountTag = findViewById(R.id.tv_taskCount_tag);
        tvTaskCountType = findViewById(R.id.tv_taskCount_type);
        tvTaskCountPriority = findViewById(R.id.tv_taskCount_priority);
        btnTaskCountFinish = findViewById(R.id.btn_taskCount_finish);
        btnTaskCountDelay = findViewById(R.id.btn_taskCount_delay);
    }
}